// 问卷调查
import React, { useReducer } from "react";
import queryApi from "../../api/query";

const UserProblemContext = React.createContext();

let proDetail;

const dataReducer = (state, action) => {
  switch (action.type) {
    case "new_problem":
      return {
        ...state,
        problem: [...state.problem, proDetail[1]],
      };
    case "update_answer":
      return {
        ...state,
        problem: action.payload.body,
      };
    case "get_problem":
      proDetail = action.payload.problem.problem;
      return {
        ...action.payload.problem,
        user: "",
        time: "",
        image: [],
        video: [],
        soundfile: [],
      };
    default:
      return state;
  }
};

let initData = {
  problem: [[], []],
};

export const UserProblemProvider = ({ children }) => {
  const [UserProblem, dispatch] = useReducer(dataReducer, initData);
  // console.log("initUserProblem---", UserProblem);

  const newProblem = () => {
    dispatch({ type: "new_problem" });
  };
  const updateProAnswer = (body) => {
    dispatch({ type: "update_answer", payload: { body } });
    // console.log("新增题目啦---", UserProblem);
  };

  const getProTemplate = async () => {
    try {
      let data = await queryApi.get("problem");
      console.log("查找问题清单模板成功---", data.data.status);
      dispatch({ type: "get_problem", payload: { problem: data.data.data } });
      // console.log("问题模板", UserProblem);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <UserProblemContext.Provider
      value={{ UserProblem, updateProAnswer, newProblem, getProTemplate }}
    >
      {children}
    </UserProblemContext.Provider>
  );
};

export default UserProblemContext;
